import random

from utils import log, template


def route_static(request):
    """
    静态资源的处理函数，读取图片并生成响应返回
    """
    filename = request.query.get('file', 'doge.gif')
    path = 'static/' + filename
    with open(path, 'rb') as f:
        header = b'HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\n\r\n'
        img = header + f.read()
        return img


# message_list = []
#
# # session 可以在服务器端实现过期功能
session = {
    'session_id': {
        'username': 'gua',
    }
}


#
#
# def template(name):
#     path = 'templates/' + name
#     with open(path, 'r', encoding='utf-8') as f:
#         return f.read()
#
#
def current_user(request):
    session_id = request.cookies.get('user', '')
    username = session.get(session_id, '【游客】')
    # username = request.cookies.get('user', '【游客】')
    return username


#
#
# def random_str():
#     """
#     生成一个随机的字符串
#     """
#     seed = 'abcdef'
#     s = ''
#     for i in range(16):
#         # 这里 len(seed) - 2 是因为我懒得去翻文档来确定边界了
#         random_index = random.randint(0, len(seed) - 2)
#         s += seed[random_index]
#     return s
#
#
# def response_with_headers(headers):
#     """
# Content-Type: text/html
# Set-Cookie: user=juran
#     """
#     header = 'HTTP/1.1 210 VERY OK\r\n'
#     header += ''.join(['{}: {}\r\n'.format(k, v) for k, v in headers.items()])
#     return header
#
#
def route_index(request):
    """
    主页的处理函数,返回主页的响应
    """
    header = 'HTTP/1.1 210 Very OK\r\nContent-Type: text/html\r\n'
    body = template('index.html')
    username = current_user(request)
    body = body.replace('{{username}}', username)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


#
#
#
#
#
# def route_login(request):
#     """
#     html页面：提交表单request,form-> Server ->routes：form = request.form()-> User.new(form)->渲染html
#     """
#     # 不考虑 session,cookie时候：
#     # header = 'HTTP/1.1 210 VERY OK\r\nContent-Type: text/html\r\n'
#     headers = {
#         'Content-Type': 'text/html',
#     }
#     log('login, cookies', request.cookies)
#     username = current_user(request)
#     if request.method == 'POST':
#         form = request.form()
#         # form是dict
#         u = User.new(form)
#         if u.validate_login():
#             # 设置一个随机字符串来当令牌使用
#             session_id = random_str()
#             session[session_id] = u.username
#             headers['Set-Cookie'] = 'user={}'.format(session_id)
#             # 浏览器会把Set-Cookie=value的值取出来
#             # 下面是把用户名存入 cookie 中
#             # headers['Set-Cookie'] = 'user={}'.format(u.username)
#             result = '登录成功'
#         else:
#             result = '用户名或者密码错误'
#
#     else:
#         result = ''
#     body = template('login.html')
#     body = body.replace('{{result}}', result)
#     body = body.replace('{{username}}', username)
#     # 是response
#     header = response_with_headers(headers)
#     r = header + '\r\n' + body
#     log('login 的响应', r)
#     return r.encode(encoding='utf-8')
#
#
# def route_register(request):
#     header = 'HTTP/1.1 210 OK\r\nContent-Type: text/html\r\n'
#     if request.method == 'POST':
#         form = request.form()
#         u = User.new(form)
#         if u.validate_register():
#             u.save()
#             result = '注册成功<br> <pre>{}</pre>'.format(User.all())
#         else:
#             result = '用户名或者密码长度必须大于2'
#     else:
#         result = ''
#     body = template('register.html')
#     body = body.replace('{{result}}', result)
#     r = header + '\r\n' + body
#     return r.encode(encoding='utf-8')
#
#
# def route_profile(request):
#     pass


route_dict = {
    '/': route_index,
    # '/login': route_login,
    # '/register': route_register,
    # '/profile': route_profile,
}
